import { getToken, setToken, removeToken, setTimeStamp, getTimeStamp } from '@/utils/auth'
import { login, getuserinfo, getuserdetailbyId } from '@/api/user'
//放置状态
const state = {
  token: getToken(),  //设置token为共享状态 初始化vuex的时候 就先从缓存中读取
  userinfo: {}    //
}
//修改状态
const mutations = {
  setToken (state, token) {
    state.token = token  //将数据设置给vuex
    //同步给缓存
    setToken(token)
  },
  removeToken (state) {
    state.token = null  //将vuex数据置空
    removeToken()   //同步到缓存
  },
  setuserinfo (state, result) {
    state.userinfo = result  //这样是响应式
    // state.userinfo = { ...result } //这样也是响应式  属于浅拷贝
  },
  //删除用户信息
  reomveUserInfo (state) {
    state.userinfo = {}
  }
}
//执行异步
const actions = {
  async login (context, data) {
    //调用接口
    const result = await login(data)  //拿到token
    context.commit('setToken', result) //设置token
    setTimeStamp()

  },
  async getuserinfo (context) {
    const result = await getuserinfo() //获取返回值
    //获取用户详情  用户的详情数据
    const baseInfo = await getuserdetailbyId(result.userId)
    context.commit('setuserinfo', { ...result, ...baseInfo })
    return result
  },
  //登出
  logout (context) {
    context.commit('removeToken')
    context.commit('reomveUserInfo')

  }

}



export default {
  namespaced: true,
  state,
  mutations,
  actions
}
